package com.itheima.reggie.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增套餐
     *
     * @param setmealDto
     * @return
     */
    @CacheEvict(value = "setmeal",allEntries = true)
    @PostMapping
    public R saveSetmeat(@RequestBody SetmealDto setmealDto) {
        log.info(setmealDto.toString());
        //将数据存入setmeal表
        setmealService.save(setmealDto);
        //获取setmealId
        Long setmealId = setmealDto.getId();

        //获取套餐内的菜品数据
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealId);
        }

        //存储数据到setmealDish表
        setmealDishService.saveBatch(setmealDishes);

        return R.success("保存套餐成功");
    }

    /**
     * 分页查询套餐数据
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R setmealQurry(Integer page, Integer pageSize, String name) {

        //设置分页构造器
        IPage<Setmeal> pageInfo = new Page<>(page, pageSize);
        //设置查询条件
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(name), Setmeal::getName, name);
        setmealService.page(pageInfo, lqw);

        Map map = new HashMap();
        //存放总数
        long total = pageInfo.getTotal();
        map.put("total", total);

        //套餐数据
        List<Setmeal> records = pageInfo.getRecords();

        List<SetmealDto> collect = records.stream().map(setmeal -> {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtil.copyProperties(setmeal, setmealDto);
            Long categoryId = setmeal.getCategoryId();
            String categoryName = categoryService.getById(categoryId).getName();
            setmealDto.setCategoryName(categoryName);

            return setmealDto;
        }).collect(Collectors.toList());

        map.put("records", collect);

        return R.success(map);
    }

    /**
     * 删除套餐
     *
     * @param ids
     * @return
     */
    @CacheEvict(value = "setmeal",allEntries = true)
    @DeleteMapping
    public R delSetmeal(@RequestParam List<Long> ids) {
        //判断删除的套餐有没有处于售卖状态的
        for (Long id : ids) {
            Setmeal setmeal = setmealService.getById(id);
            if (setmeal.getStatus() == 1) {
                return R.error("删除的套餐中,有套餐仍处于售卖状态,请停售后再删除");
            }
        }
        //调用逻辑删除.删除套餐
        setmealService.removeByIds(ids);

        //删除setmealDish中的菜品数据
        for (Long id : ids) {
            LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
            lqw.eq(SetmealDish::getSetmealId, id);
            setmealDishService.remove(lqw);
        }

        return R.success("删除成功");
    }

    /**
     * 设置套餐状态 : 启售/停售 / 批量启售/批量停售
     *
     * @param status
     * @param ids
     * @return
     */
    @CacheEvict(value = "setmeal",allEntries = true)
    @PostMapping("/status/{status}")
    public R updateDishStatus(@PathVariable Integer status, @RequestParam List<Long> ids) {
        log.info("设置套餐状态");
        log.info(status.toString());
        for (Long id : ids) {
            Setmeal setmeal = setmealService.getById(id);
            setmeal.setStatus(status);
            setmealService.updateById(setmeal);
        }

        return R.success("操作成功");
    }

    /**
     * 根据id查询套餐数据,用于回显
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R getById(@PathVariable Long id) {
        SetmealDto setmealDto = new SetmealDto();
        //将setmeal数据传递给setmealDto
        Setmeal setmeal = setmealService.getById(id);
        BeanUtil.copyProperties(setmeal, setmealDto);

        //获取套餐对应的菜品集合数据
        LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SetmealDish::getSetmealId, id);
        List<SetmealDish> list = setmealDishService.list(lqw);

        setmealDto.setSetmealDishes(list);

        return R.success(setmealDto);
    }

    /**
     * 修改套餐
     *
     * @param setmealDto
     * @return
     */
    @CacheEvict(value = "setmeal",allEntries = true)
    @PutMapping
    public R updateSetmeal(@RequestBody SetmealDto setmealDto) {
        //1.更新stemeal表
        setmealService.updateById(setmealDto);

        //2.根据id删除套餐对应的菜品数据
        LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SetmealDish::getSetmealId, setmealDto.getId());
        setmealDishService.remove(lqw);

        //3.重新添加套餐对应的菜品数据
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes = setmealDishes.stream().map(setmealDish -> {
            setmealDish.setSetmealId(setmealDto.getId());
            return setmealDish;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishes);

        return R.success("修改成功");
    }

    /**
     * 根据套餐分类id,查询套餐分类下的所有套餐
     *
     * @param categoryId
     * @return
     */
    @Cacheable(value = "setmeal", key = "#categoryId+':'+#status")
    @GetMapping("/list")
    public R getSetmeals(Long categoryId, Integer status) {
        //根据前端传进来的套餐分类id和套餐状态,查询符合条件的所有套餐
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Setmeal::getCategoryId, categoryId);
        lqw.eq(Setmeal::getStatus, status);
        List<Setmeal> setmealList = setmealService.list(lqw);

        return R.success(setmealList);
    }

    @GetMapping("/dish/{id}")
    public R getSetMeal(@PathVariable Long id) {
        Setmeal setmeal = setmealService.getById(id);
        String image = setmeal.getImage();

        return R.success(image);
    }

}
